package com.yuanfud.blog.controller;

import com.yuanfud.blog.service.FileService;
import com.yuanfud.common.encrypt.MD5Util;
import com.yuanfud.common.exception.RestException;
import com.yuanfud.common.util.ErrorCode;
import com.yuanfud.common.util.ResultBody;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@RestController
@RequestMapping("/file")
public class FileController {
    private static Logger logger= LoggerFactory.getLogger(FileController.class);
    @Autowired
    FileService fileService;

    @RequestMapping(value="/upload",method = RequestMethod.POST,consumes = "multipart/form-data")
    public ResultBody uploadFile(HttpServletRequest request,@RequestHeader String userId,@RequestHeader String loginId) throws RestException {
        ResultBody resultBody=new ResultBody();
        try {
            String attach= MD5Util.MD5Encrypt(userId+loginId);
            boolean result = fileService.uploadFile(request,attach);
            resultBody.setCode(ErrorCode.SUCCESS_OK);
            resultBody.setMsg(ErrorCode.SUCCESS_OK_MSG);
            resultBody.setData(result);
        }
        catch (Exception e){
            logger.error("上传文件错误："+e.getMessage());
            throw new RestException(ErrorCode.SYS_CONTENT_ERROR,ErrorCode.SYS_CONTENT_ERROR_MSG);
        }

        return  resultBody;
    }
}
